Angular / Services / Step 8: Interceptor
Interceptor
-
Note
interceptor
ng generate interceptor auth import { HttpInterceptorFn } from '@angular/common/http'; import { inject } from '@angular/core'; import { FirebaseAuthService } from '../services/firebase-auth.service'; export const authInterceptor: HttpInterceptorFn = (req, next) => { // const authToken = localStorage.getItem('authToken'); const token= inject(FirebaseAuthService) const authToken= "Your auth token"; const authReq = req.clone({ setHeaders: { Authorization1: `Bearer ${authToken}` } }); console.log("auth interceptor", authReq); return next(authReq); }; 2. module or config
import { ApplicationConfig, importProvidersFrom } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; import { provideAnimationsAsync } from '@angular/platform-browser/animations/async'; import { environment } from '../environments/environment'; import { AngularFireModule } from '@angular/fire/compat'; // Compatibility import import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptors } from '@angular/common/http'; import { authInterceptor } from './interceptors/auth.interceptor'; import { loggerInterceptor } from './interceptors/logger.interceptor'; export const appConfig: ApplicationConfig = { providers: [ provideRouter(routes), provideAnimationsAsync(), importProvidersFrom(AngularFireModule.initializeApp(environment.firebaseConfig)), provideHttpClient(withInterceptors([authInterceptor, loggerInterceptor])), ] };